Ext.onReady(function() {
    var viewBaseInfo;
    Ext.create('Ext.Viewport', {
        layout:'fit',
        items:[
            viewBaseInfo = createViewBasePanel()
        ]
    });
   if(objectName) {
       ajax({
           url:getRoot()+'/dataManage/view/findViewDescriptorByName',
           params:{dbName:nowDBName,viewName:objectName,baseType:now_db_type,dataBaseId:dataBase_id,dataSourceId:dataSource_id,dataSource:data_source,isLocal:isLocal},
           success:function(resp) {
               var json = jsonDecode(resp.responseText);
               if(json.success) {
                   viewBaseInfo.setData(json.root);
               }else {
                   $.message.error(json.root);
               }
           }
       });
   }
});
var algorithm_array = [
    {data:'',label:'---'},
    {data:'UNDEFINED',label:'UNDEFINED'},
    {data:'MERGE',label:'MERGE'},
    {data:'TEMPTABLE',label:'TEMPTABLE'}
];
var sqlSecurity_array = [
    {data:'',label:'---'},
    {data:'DEFINER',label:'DEFINER'},
    {data:'INVOKER',label:'INVOKER'}
];
var checkOption_array = [
    {data:'',label:'---'},
    {data:'LOCAL',label:'LOCAL'},
    {data:'CASCADED',label:'CASCADED'}
];
var createViewBasePanel = function() {
	var flag = true;
	if (now_db_type == 'mysql' || now_db_type == 'drds') {
		flag = true;
	}
	if(now_db_type == 'oracle'){
		flag = false;
	}
	var projectStore = new Ext.data.Store({
		fields:['data','label'],
		data : projectListArray
	});
   var formPanel = new IDB.FormPanel({
       layout: 'column',
       region:'north',
       title:'基本选项',
       height:160,
       defaults:{
           margin: '2 2 2 0',
           allowBlank:true
       },
       items:[{
           fieldLabel:'名称',
           name:'name',
           columnWidth:1/2,
           allowBlank:false
       },{
           fieldLabel:'算法',
           columnWidth:1/2,
           editable:false,
           xtype:'combo',
           name:'algorithm',
           triggerAction:'all',
           displayField:'label',
           valueField:'data',
           queryMode:'local',
           forceSelection:true,
           typeAhead:true,
           hidden:true,
           store:new Ext.data.Store({
               fields:['data', 'label'],
               data:algorithm_array
           })
       },{
           fieldLabel:'定义者',
           name:'definer',
           columnWidth:1/2,
           hidden:!flag
       },{
           fieldLabel:'安全性',
           columnWidth:1/2,
           editable:false,
           xtype:'combo',
           name:'sqlSecurity',
           triggerAction:'all',
           displayField:'label',
           valueField:'data',
           queryMode:'local',
           forceSelection:true,
           typeAhead:true,
           hidden:!flag,
           store:new Ext.data.Store({
               fields:['data', 'label'],
               data:sqlSecurity_array
           })
       },{
           fieldLabel:'检查选项',
           columnWidth:1/2,
           editable:false,
           xtype:'combo',
           name:'checkOption',
           triggerAction:'all',
           displayField:'label',
           valueField:'data',
           queryMode:'local',
           forceSelection:true,
           typeAhead:true,
           hidden:!flag,
           store:new Ext.data.Store({
               fields:['data' , 'label'],
               data:checkOption_array
           })
       },{
    	   columnWidth:1/2,
    	   fieldLabel:'<span style="color:red">*</span>邮箱',
    	   emptyText:'请输入部门负责人邮箱地址',
    	   allowBlank:false,
    	   name:'auserEmail',
    	   blankText:'部门负责人邮箱地址不能为空'    	   
       },{
    	   fieldLabel:'项目组',
    	   columnWidth:1/2,
       	   xtype:'combo',
       	   triggerAction:'all',
       	   displayField:'label',
       	   valueField:'data',
       	   queryMode:'local',
       	   name:'projectName',
       	   forceSelection:true,
       	   typeAhead:true,
       	   editable:false,
       	   store:projectStore
       },{
    	   columnWidth:1/2,
       	   fieldLabel:'<span style="color:red">*</span>SQL用途',
       	   allowBlank:false,
       	   name:'sqlUsage',
       	   blankText:'SQL用途说明不能为空.'
       },{
           fieldLabel:'备注',
           name:'comment',
           columnWidth:1/2,
           allowBlank:true
       }]
   });
    var sqlArea = new Ext.ux.form.field.CodeMirror({name:'content'});
   var contentPanel = new Ext.Panel({
       region:'center',title:'视图定义',layout:'fit',items:[sqlArea]
   });

   var preShowScript = function() {
       if(formPanel.isValid()) {
           if(!sqlArea.getValue()) {
               return $.message.warning('请填写视图的定义。');
           }
           var params = formPanel.getValues();
           params['content'] = sqlArea.getValue();
           params.dbName = nowDBName;
           params.baseType = now_db_type;
           params.databaseId = dataBase_id;
           params.datasourceId = dataSource_id;
           params.dataSource = data_source;
           params.isLocal = isLocal;
           if(objectName) {
               params.oldViewName = objectName;
           }
           Ext.getBody().mask('正在生成变更脚本.....');
           ajax({
               url:getRoot()+'/dataManage/view/showViewScript',
               params:params,
               success:function(resp) {
                   Ext.getBody().unmask();
                   var json = jsonDecode(resp.responseText);
                   if(json.success) {
                       showScript(json.root , params);
                   }else if(json.errorCode.substring(0 , 8) ==  'EX_0008') {
                       $.message.error(json.root);
                   }else {
                       $.message.error(json.errorCode);
                   }
               },
               failure:function() {
                   Ext.getBody().unmask();
               }
           })
       }
   };
    var onlyExecuteSQL = function(content) {
        Ext.getBody().mask('正在提交并执行变更信息.....');
        ajax({
            url:'/structure/table/executeScript.do',
            params:{script:content , dbName:nowDBName},
            success:function(resp) {
                Ext.getBody().unmask();
                var json = jsonDecode(resp.responseText);
                if(json.success) {
                    $.message.error("变更执行成功，即将重新加载视图信息。");
                    setTimeout(function() {
                        window.parent.closeViewCallBack(tabId, nowDBName);
                    } , 1000);
                }else {
                    $.message.error(json.root);
                }
            },
            failure:function(resp) {
                $.message.error(resp.responseText);
            }
        });
    };
   var showScript = function(content,params) {
       var appendButton = new Ext.Button({text:'确定',handler:function() {
           var value = sqlArea.getValue();
           params.script = value;
           params.sqlType = 'A SQL';
           params.dbName = nowDBName;
           win.getEl().mask('正在提交并执行变更信息.....');
           ajax({
               url:getRoot()+'/dataManage/executeScript',
               params:params,
               success:function(resp) {
                   win.getEl().unmask();
                   var json = jsonDecode(resp.responseText);
                   if(json.success) {
                	   if(isLocal == 'isLocal'){
                		   $.message.success("变更执行成功，关闭后，即将重新加载视图信息。");
                           setTimeout(function() {
                               if(window.parent) {
                                   window.parent.refreshViewCallBack(tabId , params['name'] , objectType , nowDBName , panelKey);
                               }else {
                                   $.message.warning('提示：该浏览器无法获取父页面信息，为避免操作冲突，请关闭该子窗口，重新打开操作。');
                               }
                           } , 1000);
                	   }else{
							win.close();
							$.feedbackMessage({type: 'success',message: json.root,showTime:5000});
                	   }
                   }else {
                       $.message.error(json.root);
                   }
               }
           });
       }});
       var closeButton = new Ext.Button({text:'关闭',handler:function() {win.close()}});
       var sqlArea = new Ext.ux.form.field.CodeMirror({readOnly:true,value:content});
       var win = new IDB.Window({
           title:(objectName ? '提交变更' : '查看SQL'),width:700,height:450,closable:true,layout:'fit',maximizable:true,
           items:[sqlArea],buttons:[appendButton , closeButton]
       });
   };
   return new Ext.Panel({
      layout:'border',items:[contentPanel , formPanel],
      setData:function(data) {
         formPanel.setTitle('基本选项 (所在库：' + nowDBName + ")");
         var fields = formPanel.getForm().getFields();
          fields.each(function(field) {
              field.setValue(data[field.getName()]);
          });
          sqlArea.setValue(formatsql(data['content']));
      },
      buttonAlign:'center',
      buttons:[{
          text:'保存修改',handler:function() {
              preShowScript();
          }
      }]
   });

};